use crate::code::attrs::Validator;
use darling::FromMeta;
use proc_macro2::TokenStream;
use quote::quote;

#[derive(Debug, Default, FromMeta)]
pub(crate) struct Length {
    pub(crate) min: Option<usize>,
    pub(crate) max: Option<usize>,
}

pub(crate) fn get_fields_length_token(validator: &Validator) -> Option<TokenStream> {
    let mut set_fields_token = TokenStream::new();
    if let Some(attr) = &validator.attr {
        if let Some(length) = &attr.length {
            eprintln!("{:?}", length);
            let field_name = validator.name;
            let mut hint_name = stringify!(field_name);
            if let Some(label) = &attr.label {
                hint_name = label;
            }
            let mut has_option = false;
            if let syn::Type::Path(syn::TypePath {
                path: syn::Path { segments, .. },
                ..
            }) = &validator.ty
            {
                if let Some(seg) = segments.last() {
                    if seg.ident == "Option" {
                        has_option = true;
                    }
                }
            }
            if let Some(max) = length.max {
                if has_option {
                    set_fields_token.extend(quote!(
                        if self.#field_name.as_ref().unwrap().len() > #max
                    ));
                } else {
                    set_fields_token.extend(quote!(
                        if self.#field_name.len() > #max
                    ));
                }
                set_fields_token.extend(quote!({
                    return Err(format!("`{}`的长度不能超过{}", #hint_name, #max).to_string());
                }));
            }
            if let Some(min) = length.min {
                if has_option {
                    set_fields_token.extend(quote!(
                        if self.#field_name.as_ref().unwrap().len() < #min
                    ));
                } else {
                    set_fields_token.extend(quote!(
                        if self.#field_name.len() < #min
                    ));
                }
                set_fields_token.extend(quote!({
                    return Err(format!("`{}`的长度不能少于{}", #hint_name, #min).to_string());
                }));
            }
        }
    }
    if set_fields_token.is_empty() {
        return None;
    }
    Some(set_fields_token)
}
